package com.charlotte.study.gupao.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器式单例
 *
 * @author junjie.ding
 * @date 2020/2/27
 */
public class ContainerSingletonDemo {

    private ContainerSingletonDemo(){}

    private static Map<String, Object> containerMap = new ConcurrentHashMap<String, Object>();

    public static Object getInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 先判断是否已经有实例了，有了的情况直接返回，不需要阻塞
        if(containerMap.containsKey(className)){
            return containerMap.get(className);
        }
        // 没有找到实例的情况，才会进行阻塞尝试获取
        synchronized (containerMap){
            if(!containerMap.containsKey(className)){
                Class<?> aClass = Class.forName(className);
                Object o = aClass.newInstance();
                containerMap.put(className, o);
                return o;
            }else{
                return containerMap.get(className);
            }
        }
    }
}
